package com.baike.shiro;

import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {

    @Resource
    private DefaultWebSecurityManager defaultWebSecurityManager;


//    将shiro的过滤器链放入spring容器中
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(){
//        创建过滤器工厂类
        ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean();
//        添加shiro内置的过滤器链
        /*
        *常用的过滤器
        * anon:不需要登陆就可以访问
        * authc:必须登陆才能访问
        * perms:登陆之后还要有权限才能访问
        * role:登陆之后要有角色才可以访问
        *
        * */
        Map<String,String> map = new LinkedHashMap<>();
//        key是url   value就是我们设置的url所对应的过滤器
        map.put("/index","anon");
        map.put("/user/update","anon");
        map.put("/user/select","anon");
        map.put("/login","anon");

//        perms 表示拥有相关的权限才能访问   里面是一个数组
        map.put("/user/delete","perms[user,delete]");//permission

//        map.put("/**","authc");

//        shiro 默认登陆页面为 login.jsp页面   springboot 不支持jsp页面  我们需要修改跳转登陆页面
        factoryBean.setLoginUrl("/toLogin");

//        设置安全管理器
        factoryBean.setSecurityManager(defaultWebSecurityManager);
        factoryBean.setFilterChainDefinitionMap(map);
        return factoryBean;
    }

//    将安全管理器 放入spring容器
    @Bean
    public DefaultWebSecurityManager defaultWebSecurityManager (@Autowired LoginRealm loginRealm){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
//        关联我们自定义的realm类
        securityManager.setRealm(loginRealm);
        return securityManager;
    }


    @Bean
    public LoginRealm loginRealm(@Autowired HashedCredentialsMatcher hashedCredentialsMatcher){
        LoginRealm loginRealm = new LoginRealm();
//        将加密方式关联我们自定义的Realm类
        loginRealm.setCredentialsMatcher(hashedCredentialsMatcher);
        return loginRealm;
    }

//    设置密码加密
    @Bean
    public HashedCredentialsMatcher hashedCredentialsMatcher (){
        HashedCredentialsMatcher matcher = new HashedCredentialsMatcher();
//        指定加密的方式
        matcher.setHashAlgorithmName("MD5");
//        设置加密的次数
        matcher.setHashIterations(3);
//        设置编码
        matcher.setStoredCredentialsHexEncoded(true);

        return matcher;
    }
}
